#include "head.h"

int loginFunc(int sockfd) {
    int password_tries_left = 4;
    int state_is;
    train_t train_name;
    train_t train_password;

    // 第一次登录
    bzero(&train_name, sizeof(train_name));
    bzero(&train_password, sizeof(train_password));

    printf("Please enter your username: ");
    fgets(train_name.data, sizeof(train_name.data), stdin);
    train_name.data[strlen(train_name.data) - 1] = '\0';
    train_name.length = strlen(train_name.data);

    printf("Please enter your password: ");
    fgets(train_password.data, sizeof(train_password.data), stdin);
    train_password.data[strlen(train_password.data) - 1] = '\0';
    train_password.length = strlen(train_password.data);
    send(sockfd, &train_name, sizeof(train_name.length)+train_name.length, MSG_NOSIGNAL);
    send(sockfd, &train_password, sizeof(train_password.length)+train_password.length, MSG_NOSIGNAL);

    while (1) {
        // 接收一个int
        recv(sockfd, &state_is,sizeof(int), 0);

        if (state_is == 0) return 0;
        else if (state_is == 1) {
            // 密码错误
            password_tries_left--;
            if (password_tries_left == 0) {
                // 密码尝试次数耗尽，返回-1
                return -1;
            }

            printf(" Password incorrect. Attempts remaining: [%d].\n", password_tries_left);
            printf("Please enter your password: ");

            bzero(&train_password, sizeof(train_password));
            fgets(train_password.data, sizeof(train_password.data), stdin);
            train_password.data[strlen(train_password.data) - 1] = '\0';
            train_password.length = strlen(train_password.data);
            send(sockfd, &train_name, sizeof(train_name.length)+train_name.length, MSG_NOSIGNAL);
            send(sockfd, &train_password, sizeof(train_password.length)+train_password.length, MSG_NOSIGNAL);
        } else if (state_is == 2) {
            // 不存在该用户
            printf("The username you entered does not exist.\n");
            bzero(&train_name, sizeof(train_name));
            bzero(&train_password, sizeof(train_password));
            printf("Please enter your username: ");
            fgets(train_name.data, sizeof(train_name.data), stdin);
            train_name.data[strlen(train_name.data) - 1] = '\0';
            train_name.length = strlen(train_name.data);

            printf("Please enter your password: ");
            fgets(train_password.data, sizeof(train_password.data), stdin);
            train_password.data[strlen(train_password.data) - 1] = '\0';
            train_password.length = strlen(train_password.data);
            send(sockfd, &train_name, sizeof(train_name.length)+train_name.length, MSG_NOSIGNAL);
            send(sockfd, &train_password, sizeof(train_password.length)+train_password.length, MSG_NOSIGNAL);


        }
    }
    return 0;
}

